# utils/report_generator.py
import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader


def generate_html_report(test_results):
    """
    生成完整的动态测试报告
    :param test_results: 包含完整测试数据的列表
    :return: 生成的HTML内容
    """
    # 计算统计数据
    total = len(test_results)
    passed = sum(1 for result in test_results if result['status'].lower() == 'pass')
    failed = total - passed
    pass_rate = (passed / total) * 100 if total > 0 else 0

    # 设置模板环境
    current_dir = os.path.dirname(os.path.abspath(__file__))
    template_dir = os.path.join(current_dir, '..', 'templates')
    env = Environment(loader=FileSystemLoader(template_dir))

    # 渲染模板
    template = env.get_template('report_template.html')
    html = template.render(
        test_results=test_results,
        total=total,
        passed=passed,
        failed=failed,
        pass_rate=f"{pass_rate:.1f}%",
        report_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )

    return html
